﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using tutors_clus.Models;
using tutors_clus.ViewModel;
using PagedList;
using System.Text.RegularExpressions;
using System.Data;
using System.IO;
using WebMatrix.WebData;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Text;
using System.Collections;

namespace tutors_clus.Controllers
{
    [Authorize(Roles = "Admin")]
    public class AdminController : Controller
    {
        tutors_clubContext db = new tutors_clubContext();
        UsersContext user = new UsersContext();
        //
        // GET: /Admin/

        public ActionResult Index()
        {
            ViewBag.a = User.Identity.Name;
            return View();
        }
        /*----------------------Quản lý giáo viên---------------------*/
        //Xem danh sách giáo viên
        public ActionResult List_teacher() 
        {
            var list_tea = db.teachers;
            return View(list_tea);
        }
        //Xem chi tiết giáo viên
        //public ActionResult Details_teacher(int id) 
        //{
        //    var detail_tea = db.teachers.Find(id);
        //    if (detail_tea == null)
        //    {
        //        return HttpNotFound();
        //    }
        //    ViewBag.cou_reg = db.courses.Where(m => m.id_tea == id);
        //    ViewBag.count = db.courses.Where(m => m.id_tea == id).Count();
        //    return View(detail_tea);
        //}
        //PartialView tìm giáo viên
        public PartialViewResult Search_teacher()
        {
            return PartialView();
        }

        //Kết quả tìm kiếm giáo viên
        public ActionResult Search_teacher_result(string searchString)
        {
            if (!String.IsNullOrEmpty(searchString))
            {
                string strSearch = ConvertToUnSign(searchString).ToLower();
                List<teacher> listnews = (from c in db.teachers select c).ToList();
                List<teacher> result = listnews.FindAll(
                        delegate(teacher math1)
                        {

                            if (ConvertToUnSign(math1.fullname_tea.ToLower()).Contains(strSearch))

                                return true;

                            else

                                return false;

                        }

                    );
                ViewBag.search = searchString;
                ViewBag.count = result.Count();
                return View(result);
            }
            else
            {
                return HttpNotFound();
            }

        }
        //Export Excel
        //public ActionResult ExportData() 
        //{
            
        //////    GridView gv = new GridView();
        //////    //string ten = "Tên giáo viên";
        //////    gv.DataSource =
        //////        db.teachers.Select(m => new
        //////    {
        //////        ten = m.fullname_tea,
        //////        ngaysinh = m.birthday_tea,
        //////        diachi = m.address_tea,
        //////        ngaydangky = m.registered_tea,
        //////        lop = m.courses.Contains(m.id_tea)
        //////    }).ToList();
        //////    gv.DataBind();
        //////    Response.ClearContent();
        //////    Response.Buffer = true;
        ////      Response.AddHeader("content-disposition", "attachment;filename=dsgv.xls");
        ////      Response.ContentType = "application/ms-excel";
        ////      Response.ContentEncoding = Encoding.Unicode;
        ////      Response.BinaryWrite(Encoding.Unicode.GetPreamble());
        ////      Response.Charset = "";
        ////      Response.Flush();
        ////      Response.End();
        //          Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.xls");
        //          return RedirectToAction("List_teacher");
        //}


        //Hiển thị lớp mà giáo viên đã đăng ký
        //public ActionResult Show_tea_registered(int id)
        //{
        //    var list_tc = db.courses.Where(m => m.id_tea == id);
        //    return PartialView(list_tc);
        //}
        //----------------------------------------------------------------------------------------

        /*--------------------------Quản lý học sinh--------------------------------------------*/
        //Danh sách học sinh
        public ActionResult List_student()
        {
            var list_stu = db.students;
            return View(list_stu);
        }
        //partialView tìm kiếm học sinh
        public PartialViewResult Search_student()
        {
            return PartialView();
        }
        //Kết quả tìm kiếm hoc sinh
        public ActionResult Search_student_result(string searchString)
        {
            if (!String.IsNullOrEmpty(searchString))
            {
                string strSearch = ConvertToUnSign(searchString).ToLower();
                List<student> listnews = (from c in db.students select c).ToList();
                List<student> result = listnews.FindAll(
                        delegate(student math)
                        {

                            if (ConvertToUnSign(math.fullname_stu.ToLower()).Contains(strSearch))

                                return true;

                            else

                                return false;

                        }

                    );
                ViewBag.search = searchString;
                ViewBag.count = result.Count();
                return View(result);
            }
            else
            {
                return HttpNotFound();
            }
        }
        //public ActionResult Details_student(int id)
        //{
        //    var detail_stu = db.students.Find(id);
        //    if (detail_stu == null)
        //    {
        //        return HttpNotFound();
        //    }
        //    ViewBag.cou_reg = db.student_course.Where(m => m.id_stu == id);
        //    ViewBag.count = db.student_course.Where(m => m.id_stu == id).Count();
        //    return View(detail_stu);
        //}
        /*Quản lý tài khoản*/
        public ActionResult Manager_Account() 
        {
            var manager_user = user.UserProfiles.Where(m=>m.UserName != "admin");
            return View(manager_user);
        }
        public ActionResult Change_sta_user(int id)
        {
            var user_accou = user.UserProfiles.Find(id);
            if (user_accou.UserId != 1)
            {
                if (user_accou.Status == true)
                {
                    user_accou.Status = false;
                }
                else
                {
                    user_accou.Status = true;   
                }
                user.Entry(user_accou).State = EntityState.Modified;
                user.SaveChanges();
            }
            return PartialView(user_accou);
        }
        /*--------------------------------Quản lý tin tức----------------------------*/
        //Hiển thị tin tức
        public ActionResult Show_News(string order)
        {
            //int pageSize = 4;
            //int pageNumber = (page ?? 1);
            //IEnumerable<news> news = db.news.OrderByDescending(y => y.create_date_new.Value.Year).ThenByDescending(m => m.create_date_new.Value.Month).ThenByDescending(d => d.create_date_new.Value.Day);
            //ViewBag.CurrentSort = "Date Desc";
            //ViewBag.Date = String.IsNullOrEmpty(order) ? "Date" : "";
            //ViewBag.Titles = order == "Title" ? "Title desc" : "Title";
            //switch (order)
            //{
            //    case "Date":
            //        return View(news.OrderBy(y => y.create_date_new.Value.Year).ThenBy(m => m.create_date_new.Value.Month).ThenBy(d => d.create_date_new.Value.Day));
            //    case "Title":
            //        return View(news.OrderBy(m => m.title_new));
            //    case "Title desc":
            //        return View(news.OrderByDescending(m => m.title_new));
            //}
            ////ViewBag.PageCount = news.ToPagedList(pageNumber, pageSize).PageCount;
            //return View(news.OrderByDescending(y => y.create_date_new.Value.Year).ThenByDescending(m => m.create_date_new.Value.Month).ThenByDescending(d => d.create_date_new.Value.Day));
            var news = db.news.OrderByDescending(y => y.create_date_new.Value.Year).ThenByDescending(m => m.create_date_new.Value.Month).ThenByDescending(d => d.create_date_new.Value.Day).ToList();;
            return View(news);
        }
        public ActionResult UpdatePosition_News(int id_news, int start, int end)
        {
            var news = db.news.Find(id_news);
            var count = db.news.Count();
            if (start < end)
            {
                var change1 = db.news.Where(i => i.sort <= end && i.sort >= start);
                foreach (var item1 in change1)
                {
                    item1.sort = item1.sort - 1;
                    db.Entry(item1).State = EntityState.Modified;

                }
                news.sort = end;

            }
            else if (start > end)
            {
                var change2 = db.news.Where(i => i.sort <= start && i.sort >= end);
                foreach (var item1 in change2)
                {
                    item1.sort = item1.sort + 1;
                    db.Entry(item1).State = EntityState.Modified;

                }
                news.sort = end;
            }
            db.SaveChanges();
            return RedirectToAction("Show_News");
        }
        //public PartialViewResult Paging(int? page)
        //{
        //    var list = db.news.OrderByDescending(y => y.create_date_new.Value.Year).ThenByDescending(m => m.create_date_new.Value.Month).ThenByDescending(d => d.create_date_new.Value.Day);
        //    int pageSize = 4; // kích cỡ của trang
        //    int pageNumber = (page ?? 1); // trang hiện tại
        //    ViewBag.PageCount = list.ToPagedList(pageNumber, pageSize).PageCount;
        //    return PartialView(list.ToPagedList(pageNumber, pageSize));
        //}
        //Đổi trạng thái tin tức
        public PartialViewResult Change_sta_news(int id)
        {
            var find_news = db.news.Find(id);
            if (find_news.status_new == true)
            {
                find_news.status_new = false;
            }
            else
            {
                find_news.status_new = true;
            }
            db.Entry(find_news).State = EntityState.Modified;
            db.SaveChanges();
            return PartialView(find_news);
        }

        //Sửa tin tức
        public ActionResult Edit_news(int id)
        {
            news find_news = db.news.Find(id);
            if (find_news == null)
            {
                return HttpNotFound();
            }
            return View(find_news);
        }
        [HttpPost]
        public ActionResult Edit_news(news news)
        {
            if (ModelState.IsValid)
            {
                news.create_date_new = DateTime.Now;
                news.sort = db.news.Where(m=>m.id_new == news.id_new).Select(m=>m.sort).FirstOrDefault();
                db.Entry(news).State = EntityState.Modified;
                db.SaveChanges();
            }
            return RedirectToAction("Show_News");
        }
        //Xem chi tiết tin
        public ActionResult Detail_news(int id=0) 
        {
            news news = db.news.Find(id);
            if (news == null)
            {
                return HttpNotFound();
            }
            return View(news);
        }
        //Thêm tin mới
        public ActionResult Create_news() 
        {
            return View();
        }
        [HttpPost]
        public ActionResult Create_news(news news)
        {
            if (ModelState.IsValid)
            {
                news.create_date_new = DateTime.Now;
                if (news.sort == null)
                {
                    news.sort = 0;
                }
                else
                {
                    news.sort = news.sort + 1;
                }
                db.news.Add(news);
                db.SaveChanges();
            }
            return RedirectToAction("Show_News");
        }
        //Xoá tin tức
        public ActionResult Delete_News(int id)
        {
            news news = db.news.Find(id);
            var changsort = db.news.Where(m => m.id_new > id);
            foreach (var item in changsort)
            {
                item.sort = item.sort - 1;
                db.Entry(item).State = EntityState.Unchanged;
                db.SaveChanges();
            }
            db.news.Remove(news);
            db.SaveChanges();
            return RedirectToAction("Show_News");
        }
        /*------------------------------Quản lý thông báo-----------------------------*/
        //Hiển thị thông báo
        public ActionResult Show_Annou()
        {
            var annou = db.annoucements.OrderByDescending(y => y.create_date_ann.Value.Year).ThenByDescending(m => m.create_date_ann.Value.Month).ThenByDescending(d => d.create_date_ann.Value.Day).ToList();
            return View(annou);
        }
        [AcceptVerbs(HttpVerbs.Post)]

        public ActionResult UpdatePosition_Annou(int id_annou, int start, int end)
        {
            var an = db.annoucements.Find(id_annou);
            var count = db.annoucements.Count();
            if (start < end)
            {
                var change1 = db.annoucements.Where(i => i.sort <= end && i.sort >= start);
                foreach (var item1 in change1)
                {
                    item1.sort = item1.sort - 1;
                    db.Entry(item1).State = EntityState.Modified;

                }
                an.sort = end;
                
            }
            else if (start > end)
            {
                var change2 = db.annoucements.Where(i => i.sort <= start && i.sort >= end);
                foreach (var item1 in change2)
                {
                    item1.sort = item1.sort + 1;
                    db.Entry(item1).State = EntityState.Modified;

                }
                an.sort = end;
            }
            db.SaveChanges();
            return RedirectToAction("Show_Annou");

        } 
        //Đổi trạng thái thông báo
        public PartialViewResult Change_sta_annou(int id)
        {
            var find_annou = db.annoucements.Find(id);
            if (find_annou.status_ann == true)
            {
                find_annou.status_ann = false;
            }
            else
            {
                find_annou.status_ann = true;
            }
            db.Entry(find_annou).State = EntityState.Modified;
            db.SaveChanges();
            return PartialView(find_annou);
        }
        //Sửa thông báo
        public ActionResult Edit_annou(int id) 
        {
            annoucement find_annou = db.annoucements.Find(id);
            if (find_annou == null)
            {
                return HttpNotFound();
            }
            return View(find_annou);
        }
        [HttpPost]
        public ActionResult Edit_annou(annoucement annou, HttpPostedFileBase file_upload)
        {
            if (ModelState.IsValid)
            {
                annou.create_date_ann = DateTime.Now;
                annou.sort = annou.sort;
                if (file_upload == null)
                {
                    db.Entry(annou).State = EntityState.Modified;
                    db.SaveChanges();
                }
                else
                {
                    var fileName = Path.GetFileName(file_upload.FileName);
                    var path = Path.Combine(Server.MapPath("~/Content/FileUpload_annou"), fileName);
                    file_upload.SaveAs(path);
                    annou.file_attach_ann = "~/Content/FileUpload_annou"+fileName;
                    db.Entry(annou).State = EntityState.Modified;
                    db.SaveChanges();
                }
            }
            return RedirectToAction("Show_Annou");
        }
        //Download file thông báo
        public FileResult Download_annou(string name)
        {
            string fileName = "~/Content/FileUpload_annou/" + name;
            string contentType = System.Net.Mime.MediaTypeNames.Application.Octet;
            return File(fileName, contentType,name);
        }
        //Xem chi tiết thông báo
        public ActionResult Detail_annou(int id = 0)
        {
            annoucement annou = db.annoucements.Find(id);
            if (annou == null)
            {
                return HttpNotFound();
            }
            return View(annou);
        }
        //Thêm tin mới
        public ActionResult Create_annou()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Create_annou(annoucement annou, HttpPostedFileBase file_upload)
        {
            if (ModelState.IsValid)
            {
                if (file_upload == null)
                {
                    annou.file_attach_ann = null;
                    //db.Entry(annou).State = EntityState.Modified;
                    //db.SaveChanges();
                }
                else
                {
                    var fileName = Path.GetFileName(file_upload.FileName);
                    var path = Path.Combine(Server.MapPath("~/Content/FileUpload_annou"), fileName);
                    file_upload.SaveAs(path);
                    annou.file_attach_ann = "~/Content/FileUpload_annou" + fileName;
                }
                if (annou.sort == null)
                {
                    annou.sort = 0;
                }
                else
                {
                    annou.sort = annou.sort + 1;
                }
                annou.create_date_ann = DateTime.Now;
                db.annoucements.Add(annou);
                db.SaveChanges();
            }
            return View(annou);
        }
        //Xoá tin tức
        public ActionResult Delete_annou(int id)
        {
            annoucement annou = db.annoucements.Find(id);
            var changsort = db.annoucements.Where(m => m.id_ann > id);
            foreach (var item in changsort)
            {
                item.sort = item.sort - 1;
                db.Entry(item).State = EntityState.Unchanged;
                db.SaveChanges();
            }
            db.annoucements.Remove(annou);
            db.SaveChanges();
            return RedirectToAction("Show_Annou");
        }
        /*--------------------------Quản lý lớp học-------------------------------*/
        //Hiển thị lớp học
        public ActionResult List_Course() 
        {
            var list_course = db.courses;
            return View(list_course);
        }
        //Đổi trạng thái lớp
        public PartialViewResult Change_sta_cou(int id)
        {
            var find_cou = db.courses.Find(id);
            if (find_cou.status_cou == true)
            {
                find_cou.status_cou = false;
            }
            else
            {
                find_cou.status_cou = true;
            }
            db.Entry(find_cou).State = EntityState.Modified;
            db.SaveChanges();
            return PartialView(find_cou);
        }
        //Xem thông tin chi tiết lớp
        //public ActionResult Detai_Course(int id) 
        //{
        //    var course = db.courses.Find(id);
        //    ViewBag.Name_tea = db.teachers.Where(t => t.id_tea == course.id_tea);
        //    ViewBag.temp = db.student_course.Where(s => s.id_cou == course.id_cou);
        //    ViewBag.count = db.student_course.Where(s => s.id_cou == course.id_cou).Count();
        //    return View(course);
        //}

        public static string ConvertToUnSign(string text)
        {
            for (int i = 33; i < 48; i++)
            {
                text = text.Replace(((char)i).ToString(), "");
            }

            for (int i = 58; i < 65; i++)
            {
                text = text.Replace(((char)i).ToString(), "");
            }

            for (int i = 91; i < 97; i++)
            {
                text = text.Replace(((char)i).ToString(), "");
            }

            for (int i = 123; i < 127; i++)
            {
                text = text.Replace(((char)i).ToString(), "");
            }

            //text = text.Replace(" ", "-"); //Comment lại để không đưa khoảng trắng thành ký tự -

            Regex regex = new Regex(@"\p{IsCombiningDiacriticalMarks}+");

            string strFormD = text.Normalize(System.Text.NormalizationForm.FormD);

            return regex.Replace(strFormD, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D');
        }
    }
}
